// import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only' // import before mqtt.
// import 'esbuild-plugin-polyfill-node/polyfills/navigator'
// import $mqtt from "./mqtt.min.js";//三端都行-app和小程序没有end回调
// import $mqtt from "./mqtt-2.18.8.min.js";//三端都行-最稳定
// import $mqtt from "./mqtt-3.0.0.min.js";//三端都行-app和小程序没有end回调
import $mqtt from "./mqtt-4.1.0.min.js";//三端都行-app和小程序没有end回调
// import $mqtt from "./mqtt-5.9.1.min.js";//报错不能用
import utils from "./util.js";
// #ifdef H5
var mqttHost = 'wss://mqtt.bus365.cn:443';
// #endif
// #ifdef MP-WEIXIN
var mqttHost = 'wxs://mqtt.bus365.cn';
// #endif
// #ifdef APP-PLUS
var mqttHost = 'wxs://mqtt.bus365.cn';
// #endif


var mqttHelper = {
	client: null,
	connect: function(mqttOptions) {
		var connectUrl = `${mqttHost}/mqtt`;
		mqttHelper.client = $mqtt.connect(connectUrl, mqttOptions);
		mqttHelper.client.on('connect', (res) => {
			console.log('connect', res) // 这是为了给自己发条消息，其它无作用
			// #ifdef APP-PLUS
			plus.nativeUI.toast("连接成功");
			// #endif
		});
		// 自动重连
		mqttHelper.client.on('reconnect', (msg) => {
			console.log('reconnect', msg)
		});
		// 错误
		mqttHelper.client.on('error', (res) => {
			console.log('error', res)
			// #ifdef APP-PLUS
			plus.nativeUI.toast("连接错误");
			// #endif
		});
		// 断开
		mqttHelper.client.on('end', (res) => {
			console.log('end', res)
		});
		// 掉线
		mqttHelper.client.on('offline', (msg) => {
			console.log('offline', msg)
		});
		// 收到消息        
		mqttHelper.client.on('message', (topic, message) => {
			// 把arrayBuffer转成字符串
			let encodedString = String.fromCharCode.apply(null, new Uint8Array(message)); // 全局发送消息
			uni.$emit('sendTopicMsg', encodedString);
		})
		// 全局监听是否有关闭mqtt的消息的事件
		uni.$on('closeMqtt', () => {
			mqttHelper.client.end(true); // 主动断开连接
		})

	},
	subscribe(topic) {
		mqttHelper.client.subscribe(topic, (res) => {
			console.log('subscribe', res)
			// #ifdef APP-PLUS
			plus.nativeUI.toast(topic + "-主题订阅成功");
			// #endif
		})
	},
	publish(topic) {
		var str = utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss');
		str += ": 欢迎使用HTML5+创建本地消息！";
		mqttHelper.client.publish('test', encodeURIComponent(str), {
			// qos: 1,
			// retain: false
		})
	},
	disconnet() {
		// #ifdef APP-PLUS
		plus.nativeUI.toast("连接断开");
		// #endif
		mqttHelper.client.end(true); // 主动断开连接
	}

}
export {
	mqttHelper
}